<template>
  <div class="dashboard-editor-container">
    <el-row style="background: #fff; padding: 16px 16px 0">
      <div class="configKnowledgeIP" style="width: 850px">
        <el-col :xs="24" :sm="24" :lg="24">
          <div class="parameType">
            <div class="title">本地化deepseek部署</div>
            <el-form label-width="150px">
              <el-row style="margin-top: 10px;">
                <el-col :xs="24" :sm="14" :lg="14">
                  <el-form-item label="deepseek服务器地址:">
                    <el-input v-model="knowledgeBase.IP" oninput="value=value.replace(/[^0-9.]/g,'')" maxlength="15"
                      placeholder="请输入知识库地址"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :xs="24" :sm="4" :lg="4" class="r-button">
                  <el-button type="primary" @click="setKnowledgeIP()">保存设置</el-button>
                </el-col>
              </el-row>
            </el-form>
          </div>
        </el-col>

        <el-col :xs="24" :sm="24" :lg="24">
          <div class="parameType">
            <div class="title">
              训练时间计划<span style="color: #409eff; margin-left: 10px">(起始时间可以大于结束时间,表示跨天) </span>
            </div>
            <el-form label-width="130px">
              <el-row style="margin-top: 10px;">
                <el-col :xs="4" :sm="4" :lg="4" style="margin-right: 12px">
                  <el-form-item label="获取素材训练时间:"></el-form-item>
                </el-col>
                <el-col :xs="12" :sm="4" :lg="4">
                  <div class="layout" style="display: flex; flex-direction: row; align-items: center">
                    <el-input v-model="trainTime.StartTime" disabled></el-input>
                    <span class="separator">至</span>
                  </div>
                </el-col>

                <el-col :xs="12" :sm="4" :lg="4">
                  <el-input v-model="trainTime.EndTime" disabled></el-input>
                </el-col>
              </el-row>
              <el-row>
                <el-col :xs="4" :sm="4" :lg="4" style="margin-right: 12px">
                  <el-form-item label="设置素材训练时间:"></el-form-item>
                </el-col>
                <el-col :xs="7" :sm="7" :lg="7">
                  <el-time-picker :popper-class="color === 'night' ? 'nightClass' : ''" v-model="startTime"
                    placeholder="开始时间" value-format="HH:mm:ss" />
                  <span class="separator">至</span>
                </el-col>
                <el-col :xs="7" :sm="7" :lg="7">
                  <el-time-picker :popper-class="color === 'night' ? 'nightClass' : ''" v-model="endTime"
                    placeholder="结束时间" value-format="HH:mm:ss" />
                </el-col>
                <el-col :xs="24" :sm="4" :lg="4" class="r-button">
                  <el-button type="primary" style="margin-left: 0px" @click="setTrainTime()">保存训练时间</el-button>
                </el-col>
              </el-row>
            </el-form>
          </div>
        </el-col>
        <el-col :xs="24" :sm="24" :lg="24">
          <div class="parameType">
            <div class="title">网络服务器</div>
            <div style="display: flex; justify-content: flex-end; padding: 10px 0">
              <el-button type="primary" @click="handleAddFileServer">添加</el-button>
            </div>
            <el-table :data="fileServerList">
              <el-table-column label="序号" type="index"></el-table-column>
              <el-table-column prop="Name" label="名称" show-overflow-tooltip></el-table-column>
              <el-table-column label="IP" width="200">
                <template slot-scope="scope">
                  {{ scope.row.SmbConf.SmbHost }}
                </template>
              </el-table-column>
              <el-table-column label="用户名" width="150" show-overflow-tooltip>
                <template slot-scope="scope">
                  {{ scope.row.SmbConf.SmbUser }}
                </template>
              </el-table-column>
              <el-table-column label="类型" width="100">
                <template slot-scope="scope">
                  {{ scope.row.Type }}
                </template>
              </el-table-column>
              <el-table-column label="操作" width="150">
                <template slot-scope="scope">
                  <el-button type="primary" size="mini" @click="handleEditFileServer(scope.row)">编辑</el-button>
                  <el-button type="danger" size="mini" @click="handleDeleteFileServer(scope.row)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            <el-dialog width="600px" :visible="netSrvDialog.visble" :title="netSrvDialog.title"
              @close="handleNetSrvDialogClose">
              <el-divider content-position="left">基本信息</el-divider>
              <el-form class="rule-container" label-width="auto" size="default" ref="refFileServer"
                :model="netSrvDialog.form" :rules="netSrvDialog.rules" :hide-required-asterisk="true">
                <div class="rule-content">
                  <el-form-item label="名称:" prop="Name">
                    <el-input v-model="netSrvDialog.form.Name"></el-input>
                  </el-form-item>
                  <el-form-item label="类型:" prop="Type">
                    <el-select v-model="netSrvDialog.form.Type" placeholder="请选择类型">
                      <el-option label="smb" value="smb"></el-option>
                    </el-select>
                  </el-form-item>
                  <el-form-item label="IP地址:" prop="IP">
                    <el-input v-model="netSrvDialog.form.IP" :maxlength="128"
                      oninput="value=value.replace(/[^0-9a-fA-F:.]/g,'')"></el-input>
                  </el-form-item>
                  <el-form-item label="端口:" prop="SmbPort">
                    <el-input v-model="netSrvDialog.form.SmbPort" :maxlength="5"
                      oninput="value=value.replace(/[^0-9]/g,'')"></el-input>
                  </el-form-item>
                  <el-form-item label="用户名:" prop="User">
                    <el-input v-model="netSrvDialog.form.User"></el-input>
                  </el-form-item>
                  <el-form-item label="密码:" prop="Password">
                    <el-input v-model="netSrvDialog.form.Password" type="password"></el-input>
                  </el-form-item>
                  <el-form-item label="确认密码:" prop="ComfirmPassword">
                    <el-input v-model="netSrvDialog.form.ComfirmPassword" type="password"></el-input>
                  </el-form-item>
                </div>
              </el-form>
              <el-divider class="lineToFooter"></el-divider>
              <template slot="footer">
                <el-button @click="netSrvDialog.visble = false">取消</el-button>
                <el-button type="primary" @click="handleNetSrvDialogConfirm">确定</el-button>
              </template>
            </el-dialog>
          </div>
        </el-col>
      </div>
    </el-row>
  </div>
</template>

<script>
import { Task_URLS } from "@/views/Material/api/request";
import { connrequest, directRequest } from "@/api/firstPage";
import { noTokenRequest } from "@/api/material";

export default {
  name: "KnowledgeBaseSet",
  data() {
    return {
      knowledgeBase: {
        IP: ""
      },
      trainTime: {
        StartTime: "",
        EndTime: ""
      },
      startTime: null,
      endTime: null,
      color: "",
      fileServerList: [],
      netSrvDialog: {
        visble: false,
        title: "",
        action: 1, //1 添加 2修改
        form: {
          ID: 0,
          Name: "",
          Type: "smb",
          IP: "",
          SmbPort: "",
          User: "",
          Password: "",
          ComfirmPassword: ""
        },
        rules: {
          Name: [{ required: true, message: "请输入名称", trigger: "blur" }],
          IP: [
            { required: true, message: "请输入IP地址", trigger: "blur" },
            {
              validator: (rule, value, callback) => {
                const reg =
                  /^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/;
                if (!reg.test(value)) {
                  callback(new Error("请输入正确的IP地址"));
                } else {
                  callback();
                }
              }
            }
          ],
          SmbPort: [
            { required: true, message: "请输入端口", trigger: "blur" },
            {
              validator: (rule, value, callback) => {
                const reg =
                  /^([1-9][0-9]{0,3}|[1-5][0-9]{4}|6[0-4][0-9]{3}|65[0-4][0-9]{2}|655[0-2][0-9]|6553[0-5])$/;
                if (!reg.test(value)) {
                  callback(new Error("请输入正确的端口"));
                } else {
                  callback();
                }
              }
            }
          ],
          User: [{ required: true, message: "请输入用户名", trigger: "blur" }],
          Password: [{ required: true, message: "请输入密码", trigger: "blur" }],
          ComfirmPassword: [
            { required: true, message: "请输入确认密码", trigger: "blur" },
            {
              validator: (rule, value, callback) => {
                if (value !== this.netSrvDialog.form.Password) {
                  callback(new Error("两次输入密码不一致"));
                } else {
                  callback();
                }
              },
              trigger: "blur"
            }
          ]
        }
      }
    };
  },
  mounted() {
    this.color = localStorage.getItem("isNightMode") || "night";
    this.getData();
    this.getFileServer();
  },
  methods: {
    async getData() {
      await this.getKnowledgeIP();
      await this.getTrainTime();
    },
    async getKnowledgeIP() {
      const res = await connrequest("GetKnowledgebaseConf");
      if (res.Status.StatusCode === 0) {
        this.knowledgeBase = { ...res.Data };
        localStorage.setItem("KnowledgeIP", res?.Data?.IP);
      }
    },
    async setKnowledgeIP() {
      let ipAddress =
        /^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/;
      if (!ipAddress.test(this.knowledgeBase.IP)) {
        this.$message.error("请输入正确的IP地址");
        return false;
      }
      const data = {
        Data: {
          IP: this.knowledgeBase.IP
        }
      };
      const res = await connrequest("SetKnowledgebaseConf", data);
      if (res.Status.StatusCode === 0) {
        this.$message.success("修改知识库地址成功");
        this.getKnowledgeIP();
      }
    },
    async getTrainTime() {
      if (this.knowledgeBase.IP) {
        const res = await noTokenRequest(Task_URLS.getTrainTime);
        if (res.Status.StatusCode === 0) {
          this.trainTime = { ...res.Data };
        }
      } else {
        this.$message.warning("请先设置知识库IP");
      }
    },
    async setTrainTime() {
      if (this.knowledgeBase.IP) {
        if (!this.startTime || !this.endTime) {
          this.$message.warning("请选择完整的训练时间范围");
          return;
        }
        const data = {
          StartTime: this.startTime, // e.g., '14:30:00'
          EndTime: this.endTime // e.g., '12:00:00'
        };
        await noTokenRequest(Task_URLS.setTrainTime, data);
        this.getTrainTime();
      } else {
        this.$message.warning("请先设置知识库IP");
      }
    },
    async getFileServer() {
      const res = await directRequest("/zyq/get_file_server", {});
      if (res.Status.StatusCode === 0) {
        this.fileServerList = res.Data;
      } else {
        this.$message.error(res.Status.StatusMsg);
      }
    },
    handleAddFileServer() {
      this.netSrvDialog.visble = true;
      this.netSrvDialog.title = "添加网络服务器";
      this.netSrvDialog.action = 1;
    },
    handleEditFileServer(row) {
      this.netSrvDialog.visble = true;
      this.netSrvDialog.title = "修改网络服务器";
      this.netSrvDialog.action = 2;
      this.netSrvDialog.form.ID = row.ID;
      this.netSrvDialog.form.Name = row.Name;
      this.netSrvDialog.form.Type = row.Type;
      this.netSrvDialog.form.IP = row.SmbConf.SmbHost;
      this.netSrvDialog.form.SmbPort = row.SmbConf.SmbPort;
      this.netSrvDialog.form.User = row.SmbConf.SmbUser;
      this.netSrvDialog.form.Password = row.SmbConf.SmbPwd;
      this.netSrvDialog.form.ComfirmPassword = row.SmbConf.SmbPwd;
    },
    handleDeleteFileServer(row) {
      this.$confirm("此操作将永久删除该文件服务器, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(async () => {
        const data = {
          Action: 3,
          FileServer: {
            ID: row.ID
          }
        };
        const res = await directRequest("/zyq/edit_file_server", data);
        if (res.Status.StatusCode === 0) {
          this.$message.success("删除成功");
          await this.getFileServer();
        } else {
          this.$message.error(res.Status.StatusMsg);
        }
      });
    },
    handleNetSrvDialogConfirm() {
      this.$refs.refFileServer.validate(async (valid) => {
        if (valid) {
          if (this.netSrvDialog.action === 1) {
            if (this.netSrvDialog.form.Type === "smb") {
              const form = this.netSrvDialog.form;
              const data = {
                Action: 1,
                FileServer: {
                  ID: Math.floor(Date.now() / 1000),
                  Name: form.Name,
                  Type: form.Type,
                  SmbConf: {
                    SmbHost: form.IP,
                    SmbUser: form.User,
                    SmbPort: form.SmbPort,
                    SmbPwd: form.Password
                  }
                }
              }
              const res = await directRequest("/zyq/edit_file_server", data);
              if (res.Status.StatusCode === 0) {
                this.$message.success("添加成功");
                this.netSrvDialog.visble = false;
                await this.getFileServer();
                this.handleResetFileServerForm();
              } else {
                this.$message.error(res.Status.StatusMsg);
              }
            }
          }
          if (this.netSrvDialog.action === 2) {
            const data = {
              Action: 2,
              FileServer: {
                ID: this.netSrvDialog.form.ID,
                Name: this.netSrvDialog.form.Name,
                Type: this.netSrvDialog.form.Type,
                SmbConf: {
                  SmbHost: this.netSrvDialog.form.IP,
                  SmbUser: this.netSrvDialog.form.User,
                  SmbPwd: this.netSrvDialog.form.Password
                }
              }
            };
            const res = await directRequest("/zyq/edit_file_server", data);
            if (res.Status.StatusCode === 0) {
              this.$message.success("修改成功");
              this.netSrvDialog.visble = false;
              await this.getFileServer();
              this.handleResetFileServerForm();
            } else {
              this.$message.error(res.Status.StatusMsg);
            }
          }
        }
      });
    },
    handleResetFileServerForm() {
      this.netSrvDialog.form = {
        ID: 0,
        Name: "",
        Type: "",
        IP: "",
        User: "",
        Password: "",
        ComfirmPassword: ""
      };
    },
    handleNetSrvDialogClose() {
      this.netSrvDialog.visble = false;
      this.handleResetFileServerForm();
    }
  }
};
</script>

<style lang="scss" scoped>
.el-form {
  .r-button {
    margin-left: 30px;
  }
}

.separator {
  margin-left: 2px;
}

.night {
  .parameType {
    background: #303445;
    box-shadow: none !important;
    border: 1px solid #3f4456;

    .title {
      border-bottom: 1px solid #3f4456;
    }
  }

  .el-time-picker,
  .el-date-editor {
    background: #303445;
    border: 1px solid #414556;
  }

  .separator {
    color: white;
  }

  .el-date-editor {
    border: none;
  }
}

/* 简化时间选择器样式 */
.el-time-picker__popper {
  .el-time-spinner {
    overflow-y: auto !important;
    max-height: 200px;
    -webkit-overflow-scrolling: touch;
  }

  .el-time-spinner__wrapper {
    overflow-y: auto !important;
    max-height: 200px;
  }
}

.nightClass {
  .el-time-panel__footer {
    border-top: 1px solid #5a6675;
    background-color: #314054;
  }
}
</style>
